package com.jhgsys.internal.system.controller;


import com.alibaba.fastjson.JSONArray;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.*;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.system.dto.MenuDto;
import com.jhgsys.internal.system.entity.Menu;
import com.jhgsys.internal.system.entity.MenuModel;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IMenuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author MrBird
 */
@Slf4j
@RestController
@RequestMapping("menu")
public class MenuController extends BaseController {

    @Autowired
    private IMenuService menuService;

    @GetMapping("{userName}")
    public FebsResponse getUserMenus(@NotBlank(message = "{required}") @PathVariable String userName) throws FebsException {
        User currentUser = getCurrentUser();
        if (!StringUtils.equalsIgnoreCase(userName, currentUser.getUserName())) {
            throw new FebsException("您无权获取别人的菜单");
        }
        MenuTree<Menu> userMenus = this.menuService.findUserMenus(userName);
        return new FebsResponse().data(userMenus);
    }

    @GetMapping("tree")
    @RequiresPermissions(value={"menu:view", "role:view"},logical= Logical.OR)
    public FebsResponse getMenuTree(Menu menu) throws FebsException {
        try {
            if (hasHeadCompanyRole()) {
                //系统管理员角色看全部
                MenuTree<Menu> menus = this.menuService.findMenus(menu);
                return new FebsResponse().success().data(menus.getChilds());
            }
//            //其他人只能看自己的角色下面的权限
            menu.setRoleIds(getCurrentUser().getRoleId());
            MenuTree<Menu> menus = this.menuService.findMenus(menu);
            return new FebsResponse().success().data(menus.getChilds());
        } catch (Exception e) {
            String message = "获取菜单树失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("treeNew")
    @RequiresPermissions(value={"menu:view", "role:view"},logical= Logical.OR)
    public Object getMenuTreeNew(QueryRequest request, Menu menu) throws FebsException {
        try {
            if (hasHeadCompanyRole()) {
                //系统管理员角色看全部
                if(StringUtils.isNotBlank(menu.getMenuName())){
                    List<MenuTreeNew<Menu>> menus = this.menuService.searchMenus(request,menu);
                    MenuModel model = new MenuModel(menus,this.menuService.serchMenusCount(menu));
                    return model;
                }else{
                    MenuTreeNew<Menu> menus = this.menuService.findMenusA(request,menu);
                    Integer total = this.menuService.findMenusCount(menu);
                    MenuModel model = new MenuModel(menus.getChildren(),total);
                    return model;
                }
            }
            if(StringUtils.isNotBlank(menu.getMenuName())){
                menu.setRoleIds(getCurrentUser().getRoleId());
                List<MenuTreeNew<Menu>> menus = this.menuService.searchMenus(request,menu);
                MenuModel model = new MenuModel(menus,this.menuService.serchMenusCount(menu));
                return model;
            }else{
            //其他人只能看自己的角色下面的权限
                menu.setRoleIds(getCurrentUser().getRoleId());
                MenuTreeNew<Menu> menus = this.menuService.findMenusA(request,menu);
                Integer total = this.menuService.findMenusCount(menu);
                return new MenuModel(menus.getChildren(),total);
            }
        } catch (Exception e) {
            String message = "获取菜单树失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("treeSelect")
    @RequiresPermissions(value={"menu:view", "role:view"},logical= Logical.OR)
    public Object getMenuTreeSelect(QueryRequest request, Menu menu) throws FebsException {
        try {
            if (hasHeadCompanyRole()) {
                //系统管理员角色看全部
                Object menus = this.menuService.findMenusB(menu);
                return menus;
            }
//            //其他人只能看自己的角色下面的权限
            menu.setRoleIds(getCurrentUser().getRoleId());
            Object menus = this.menuService.findMenusB(menu);
            return menus;
        } catch (Exception e) {
            String message = "获取菜单树失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("treeForTopLevel")
    @RequiresPermissions(value={"menu:view", "role:view"},logical= Logical.OR)
    public FebsResponse treeForTopLevel(Menu menu) throws FebsException {
        try {
            if (!hasHeadCompanyRole()) {
                //其他人只能看自己的角色下面的权限
                menu.setRoleIds(getCurrentUser().getRoleId());
            }
            MenuTree<Menu> menus = this.menuService.findMenus(menu);
            List<MenuTree<Menu>> childList = menus.getChilds();
            childList.forEach(c->{
                c.setChilds(null);
            });
            return new FebsResponse().success().data(childList);
        } catch (Exception e) {
            String message = "获取菜单失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("新增菜单/按钮")
    @PostMapping
    @RequiresPermissions("menu:add")
    public FebsResponse addMenu(@RequestBody Menu menu) throws FebsException {
        try {
            menu.setCreatedBy(getCurrentUser().getUserName());
            this.menuService.createMenu(menu);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增菜单/按钮失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("删除菜单/按钮")
    @GetMapping("delete/{menuIds}")
    @RequiresPermissions("menu:delete")
    public FebsResponse deleteMenus(@NotBlank(message = "{required}") @PathVariable String menuIds) throws FebsException {
        try {
            Menu menu = new Menu();
            menu.setDeletedBy(getCurrentUser().getUserName());
            menu.setDeletedTime(new Date());
            menu.setDeletedFlg(FebsConstant.INVALID);
            this.menuService.updateMenuDeletedFlg(menuIds,menu);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除菜单/按钮失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("修改菜单/按钮")
    @PostMapping("update")
    @RequiresPermissions("menu:update")
    public FebsResponse updateMenu(@RequestBody Menu menu) throws FebsException {
        try {
            menu.setUpdatedBy(getCurrentUser().getUserName());
            this.menuService.updateMenu(menu);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改菜单/按钮失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("excel")
    @RequiresPermissions("menu:export")
    public void export(Menu menu, HttpServletResponse response) throws FebsException {
        try {
            // excel导出,不用框架自带的，重写
            this.menuService.exportData( menu, response);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

}
